<template>
  <a-spin :spinning="spinning" tip="加载中...">
  <a-card :bordered="false">
    <h3>{{id == 'null' ? '新增' : '编辑'}}消息</h3>
    <a-form-model
      ref="rulesForm"
      :model="form"
      :rules="rules"
      :labelCol="{ lg: { span: 6 }, sm: { span: 8 } }"
      :wrapperCol="{ lg: { span: 14 }, sm: { span: 16 } }"
    >
      <a-form-model-item label="投放小程序" prop="configId">
        <a-select v-model="form.configId" mode="multiple" placeholder="请选择投放小程序" show-search :filter-option="filterOption">
          <a-select-option :value="item.weid" v-for="item in brandList" :key="item.weid">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="消息类型" prop="advicesType">
        <a-select v-model="form.advicesType" placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option value="" disabled>请选择消息类型</a-select-option>
          <a-select-option :value="item.id" v-for="item in advicesTypeList" :key="item.id">
            {{ item.advicesName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="消息内容" prop="advicesContent">
        <a-textarea
            v-model.trim="form.advicesContent"
            :maxLength="300"
            placeholder="请输入具体消息内容，限300字以内"
            :rows="3"
            allowClear
          />
      </a-form-model-item>
      <a-form-model-item  label="发送方式" prop="sendWay">
        <a-radio-group v-model="form.sendWay">
          <a-radio :value="0">立即推送</a-radio>
          <a-radio :value="1">定时发送</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.sendWay == 1" class="hidden-title" label="定时发送" prop="sendTime">
        <a-date-picker
          v-model="form.sendTime"
          show-time
          valueFormat="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-model-item>
      <a-form-model-item label="发送对象" prop="sendObject">
        <a-radio-group v-model="form.sendObject">
          <a-radio :value="0">全部用户</a-radio>
          <a-radio :value="1">按身份选择</a-radio>
          <a-radio :value="2">手动上传</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.sendObject == 1" class="hidden-title" label="按身份选择" prop="identityId">
        <a-checkbox-group v-model="form.identityId">
          <a-checkbox :value="item.id"  v-for="item in identityList" :key="item.id">{{ item.identityName }}</a-checkbox>
        </a-checkbox-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.sendObject == 2" class="hidden-title" label="手动上传" prop="sendObj">
        <SendUser ref="sendUser" v-if="uploadListId || uploadListId == null" :id="uploadListId"></SendUser>
      </a-form-model-item>
      <a-form-model-item label="跳转方式" prop="jumpWay">
        <a-select v-model="form.jumpWay" placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option :value="0">小程序</a-select-option>
          <a-select-option :value="1">不跳转</a-select-option>
          <a-select-option :value="2">自定义链接</a-select-option>
          <a-select-option :value="3">视频号</a-select-option>
          <a-select-option :value="4">话题</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item v-if="form.jumpWay==0" label="appid" prop="appId">
        <a-input
            v-model.trim="form.appId"
            placeholder=""
            allowClear
          />
      </a-form-model-item>
      <a-form-model-item v-if="form.jumpWay !== '' && form.jumpWay!=1 && form.jumpWay!=4" label="落地页" prop="landingPage">
        <a-input
            v-model.trim="form.landingPage"
            placeholder=""
            allowClear
          />
      </a-form-model-item>
      <a-form-model-item label="话题" v-if="form.jumpWay == 4" prop="jumpWay">
        <a-select v-model="form.topicId"  placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option v-for="topic in topicList" :value="topic.id+''" :key="topic.id">{{topic.topicName}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button style="margin-right: 8px" @click="handleBack">取消</a-button>
        <a-button htmlType="submit" @click="handleSubmit" type="primary" >保存</a-button>
      </a-form-model-item>
    </a-form-model>
  </a-card>
  </a-spin>
</template>
<script>
   import { brandList } from '../../components/brandList.js'
  import { advicesAdd, advicesTypeList, advicesEdit, uploadList, advicesDetail, batchUploadClear} from '@/api/micromall/communityMarketing'
  import { topicPage } from '@/api/micromall/communityContent'
  import { identityList } from '@/api/micromall/communityUser'
  import SendUser from '../../components/SendUser'
  import { mapGetters } from 'vuex'
  export default {
    components: {
      SendUser
    },
    data() {
      return {
        uploadListId: '',
        topicList: [],
        identityList: [],
        brandList,
        advicesTypeList: [],
        id: this.$route.params.id,
        spinning: false,
        form: {
          sendObject: 0,
          jumpWay: 1,
          topicId: '',
          configId: [],
          advicesType: '',
          advicesContent: '',
          sendWay: 0,
          identityId: [],
          sendTime: '',
          landingPage: ''
        },
        rules: {
          configId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          advicesType: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          advicesContent: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          sendWay: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          sendTime: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          sendObject: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          identityId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          jumpWay: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          appId: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          landingPage: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          topicId: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      this.getAdvicesTypeList()
      this.getIdentityList()
      this.getTopicPage()
      this.getDetails()
    },
    computed: {
    },
    mounted() {
    },
    beforeDestroy() {
    },
    methods: {
      // 获取详情
      getDetails() {
        const id = this.$route.params.id
        if (id == 'null') {
          this.uploadListId = null
          return
        }
        const data = {
          id,
          current:1
        }
        advicesDetail(data).then(res => {
          if (res.code == 200) {
            const { sendObject, identityId, configId, sendObjectIdentityList } = res.data.records[0]
            this.uploadListId = res.data.records[0].id
            this.form = {
              ...res.data.records[0],
              identityId: sendObject == 1 ? sendObjectIdentityList.map(e => e.id) : [],
              configId: configId ? configId.split(',') : []
            }
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 消息类型
      getAdvicesTypeList() {
        advicesTypeList({status: '0'}).then(res => {
          if (res.code == 200) {
            const { records} = res.data
            this.advicesTypeList = records
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 获取话题列表
      getTopicPage() {
        const data = {
          pageNo: 1,
          pageSize: 1000,
          options: 1
        }
        topicPage(data).then(res => {
          if (res.code === 200) {
            const { records} = res.data
            this.topicList = records
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },
      

      // 获取身份标识
      getIdentityList() {
        identityList({}).then(res => {
          if (res.code === 200) {
            this.identityList = res.data
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },
        // 获取当前时间
      getTime() {
        const nowdate = new Date()
        const year = nowdate.getFullYear(),
          month = this.checkTime(nowdate.getMonth() + 1),
          date =  this.checkTime(nowdate.getDate()),
          h =  this.checkTime(nowdate.getHours()),
          m = this.checkTime(nowdate.getMinutes()),
          s =  this.checkTime(nowdate.getSeconds())
        return `${year}-${month}-${date} ${h}:${m}:${s}`
      },

      // 时间补位
      checkTime(i) {
        if (i < 10) {
          i = '0' + i
        }
        return i
      },

       ...mapGetters(['nickname', 'avatar', 'userInfo']),

      // 确认同步
      handleSubmit() {
        const advicesAddOrEdit = this.id == 'null' ? advicesAdd : advicesEdit
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            const {sendObject, identityId, configId, sendTime, sendWay, jumpWay, landingPage, appId, topicId} = this.form
            if (sendObject == 2 && !this.$refs['sendUser'].total ) {
              this.$message.error('请添加发送对象！')
              return
            }
            const data = {
              ...this.form,
              identityId: sendObject == 1 ? identityId : null,
              configId: configId.join(','),
              logInUserId: this.userInfo().id,
              sendTime: sendWay == 1 ? sendTime : this.getTime(),
              appId: jumpWay === 0 ? appId : null,
              landingPage: jumpWay !== '' && jumpWay!=1 && jumpWay!=4 ? landingPage : null,
              topicId: jumpWay == 4 ? topicId : null,
            }
            this.spinning = true
            advicesAddOrEdit(data).then(res => {
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.spinning = false
                this.$message.error(res.msg || res.message)
              }
            })
            .catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      // 清楚缓存
      getBatchUploadClear() {
        const data = {
          logInUserId: this.userInfo().id
        }
        batchUploadClear(data).then(res => {
          if (res.code === 200) {
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      //返回
      handleBack() {
        this.getBatchUploadClear()
        this.$router.go(-1)
      },

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
    }
  }
</script>
<style lang="less" scoped>
  .hidden-title /deep/ .ant-form-item-label > label {
    visibility: hidden;
  }
  /deep/.ant-checkbox-wrapper + .ant-checkbox-wrapper {
    margin-left: 0;
    margin-right: 8px;
  }
</style>
